﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Threading;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DSLOrder
{
    public partial class Log : Form
    {
        public Log()
        {
            InitializeComponent();
        }
        Common Init = new Common();
        MsSqlHelper mssql = new MsSqlHelper();
        Api Api = new Api();

        DataTable dtsrc = null;
        DataTable newdt = null;
        JToken jToken = null;

        private void Log_Load(object sender, EventArgs e)
        {
            txtLog.Text = "";
        }

        /// <summary>
        /// 获取ToKen
        /// </summary>
        public void GetToken()
        {
            try
            {
                string TokenJSON = Api.GetToKen();
                JObject jObject = (JObject)JsonConvert.DeserializeObject(TokenJSON);

                string code = (string)jObject["code"];
                if (code == "200")
                {
                    Api.Token = (string)jObject["data"];
                    Init.WriteLog("ToKen获取成功！", false);
                    GetOrder();
                }
                else
                {
                    Init.WriteLog("ToKen获取失败：" + TokenJSON, false);
                    GetToken();
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                GetToken();
            }
        }
        /// <summary>
        /// 获取报价单
        /// </summary>
        public void GetOrder()
        {
            try
            {
                string OrderJSON = Api.GetOrder();
                JObject jObject = (JObject)JsonConvert.DeserializeObject(OrderJSON);
                string code = (string)jObject["code"];
                if (code == "200")
                {
                    jToken = jObject["data"];
                    Init.WriteLog("获取询价表成功！", false);
                    ToTable();
                }
                else
                {
                    Init.WriteLog("获取询价表失败：" + OrderJSON, false);
                    GetOrder();
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                GetOrder();
            }
        }

        public void ToTable()
        {
            try
            {
                //dtsrc.Clear();
                //dtsrc.Columns.Clear();
                dtsrc = new DataTable();
                dtsrc.Columns.Add(new DataColumn("serialNumber", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("supplierId", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("supplierName", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("supplierItemId", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("supplierItemName", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("manufacturer", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("nationalMedicine", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("barCode", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("subUserId", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("subUserName", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("userId", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("userName", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("itemId", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("itemName", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("ypgg", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("dw", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("qtyNeed", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("qtySupplierOffer", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("price", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("lotNumber", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("productionDate", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("validityPeriod", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("comment", Type.GetType("System.String")));
                dtsrc.Columns.Add(new DataColumn("remark", Type.GetType("System.String")));
                foreach (JObject item in (IEnumerable<JToken>)jToken)
                {
                    DataRow dr = dtsrc.NewRow();
                    dr["serialNumber"] = item["serialNumber"].ToString();
                    dr["supplierId"] = item["supplierId"].ToString();
                    dr["supplierName"] = item["supplierName"].ToString();

                    string supplierItemId = mssql.GetString("select supplierItemId from csc_user_bind_goods(nolock) where itemId='" + item["itemId"].ToString() + "'");
                    if (!string.IsNullOrEmpty(supplierItemId))
                    {
                        dr["supplierItemId"] = supplierItemId;
                    }
                    else
                    {
                        dr["supplierItemId"] = item["supplierItemId"].ToString();
                    }
                    dr["supplierItemName"] = item["supplierItemName"].ToString();
                    dr["manufacturer"] = item["manufacturer"].ToString();
                    dr["nationalMedicine"] = item["nationalMedicine"].ToString();
                    dr["barCode"] = item["barCode"].ToString();
                    dr["subUserId"] = item["subUserId"].ToString();
                    dr["subUserName"] = item["subUserName"].ToString();
                    dr["userId"] = item["userId"].ToString();
                    dr["userName"] = item["userName"].ToString();
                    dr["itemId"] = item["itemId"].ToString();
                    dr["itemName"] = item["itemName"].ToString();
                    dr["ypgg"] = item["ypgg"].ToString();
                    dr["dw"] = item["dw"].ToString();
                    dr["qtyNeed"] = item["qtyNeed"].ToString();
                    dr["qtySupplierOffer"] = item["qtySupplierOffer"].ToString();
                    dr["price"] = item["price"].ToString();
                    dr["lotNumber"] = item["lotNumber"].ToString();
                    dr["productionDate"] = item["productionDate"].ToString();
                    dr["validityPeriod"] = item["validityPeriod"].ToString();
                    dr["comment"] = item["comment"].ToString();
                    dtsrc.Rows.Add(dr);
                }
                Init.WriteLog("询价表转表成功！", false);
                ToPrice();
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                ToTable();
            } 
        }

        public void ToPrice()
        {
            decimal n = Init.pricen;
            string sql = "";
            try
            {
                DataTable dt = new DataTable();
                sql = "select b.spmch+b.spmch as supplierItemName,case when isnull(b.zdsj,0)=0 then 0 else isnull(b.zdsj,0)+(" + n + "/jlgg) end as price,rtrim(isnull(b.zdsj,0))+'_'+rtrim(" + n + "/jlgg) as remark,b.shl as qtySupplierOffer,rtrim(b.pihao) as lotNumber,b.sxrq as validityPeriod,b.baozhiqi as productionDate,a.itemId,a.supplierItemId from csc_user_bind_goods a(nolock) left join V_Api_Goods b(nolock) on a.supplierItemId=b.spid";
                dt = mssql.ExecuteDt(sql);
                for (int i = 0; i < dtsrc.Rows.Count; i++)
                {
                    string find = dtsrc.Rows[i]["itemId"].ToString();
                    DataRow[] dr = dt.Select("itemId = '" + find + "' ");
                    if (dr.Length > 0)
                    {
                        dtsrc.Rows[i]["supplierItemName"] = dr[0]["supplierItemName"].ToString();
                        dtsrc.Rows[i]["price"] = decimal.Round(decimal.Parse(dr[0]["price"].ToString()), 2).ToString();
                        dtsrc.Rows[i]["qtySupplierOffer"] = dr[0]["qtySupplierOffer"].ToString();
                        dtsrc.Rows[i]["lotNumber"] = dr[0]["lotNumber"].ToString();
                        dtsrc.Rows[i]["validityPeriod"] = dr[0]["validityPeriod"].ToString();
                        dtsrc.Rows[i]["productionDate"] = dr[0]["productionDate"].ToString();
                        dtsrc.Rows[i]["supplierItemId"] = dr[0]["supplierItemId"].ToString();
                        dtsrc.Rows[i]["remark"] = dr[0]["remark"].ToString();
                    }
                }
                newdt = new DataTable();
                newdt = dtsrc.Clone();
                DataRow[] newdr = dtsrc.Select("supplierItemName<>''");
                for (int i = 0; i < newdr.Length; i++)
                {
                    newdt.ImportRow((DataRow)newdr[i]);
                }
                newdt.DefaultView.Sort = "supplierItemId,supplierItemName";
                Init.WriteLog("报价成功！", false);
                UpOrder();
            }
            catch (Exception ex)
            {

                Init.WriteLog(ex.ToString(), true);
                ToPrice();
            }
        }

        public void UpOrder()
        {
            try
            {
                string requestData = readStockToJson(newdt);
                string result = Api.UpOrder(requestData);
                Init.WriteLog("上传报价失败！" + result, false);
                JObject jObject = (JObject)JsonConvert.DeserializeObject(result);
                string code = (string)jObject["code"];
                if (code == "200")
                {
                    Init.WriteLog("上传报价表成功！", false);                    
                }
                else
                {
                    Init.WriteLog("上传报价失败！" + result, false);
                    UpOrder();
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                UpOrder();
            } 
        }

        public string readStockToJson(DataTable dt)
        {
            string stockJsonStr = "";

            if (dt != null)
            {
                List<object> list = new List<object>();
                //foreach (DataTable table in ds.Tables)
                //{
                foreach (DataRow row in dt.Rows)
                {
                    Dictionary<string, object> dictionary = new Dictionary<string, object>();
                    foreach (DataColumn column in dt.Columns)
                    {
                        string a = column.ColumnName.ToLower();
                        if (a != "remark")
                        {
                            dictionary.Add(a, row[column]);
                        }
                    }
                    list.Add(dictionary);
                }
                // }
                Dictionary<string, object> dictionary2 = new Dictionary<string, object>();
                dictionary2.Add("supplierItemPriceList", list);
                stockJsonStr = JsonConvert.SerializeObject(dictionary2);
            }
            return stockJsonStr;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetToken();
        }
    }
}
